package cn.bluech.lib.rxandroid;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

/**
 * Description:
 * Create by Codeant on 2019/5/20.
 */
public class RxBus {

    private static RxBus instance;
    private final PublishSubject<Object> bus;


    public static RxBus getInstance(){
        if(null!=instance)
            return instance;
        synchronized (RxBus.class){
            if(null==instance)
                instance = new RxBus();
        }

        return instance;
    }

    private RxBus(){
        bus = PublishSubject.create();
    }

    public <T> Disposable register(Class<T> evtCls, Listener<T> listener){
        return bus.ofType(evtCls)
                .observeOn(Schedulers.io())
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<T>() {
                    @Override
                    public void accept(T t) throws Exception {
                        listener.onEvent(t);
                    }
                });
    }

    public void unregister(Disposable disposable){
        //CompositeDisposable aa;
        disposable.dispose();
    }

    /**
     * 发送事件
     * @param event : event object(事件的内容)
     */
    public void post(Object event){
        bus.onNext(event);
    }




    public interface Listener<T> {
        void onEvent(T evt);
    }
}
